package com.lhwzs.user.servlets;

import com.google.gson.Gson;
import com.lhwzs.myssm.myspringmvc.ViewBaseServlet;
import com.lhwzs.myssm.util.StringUtil;
import com.lhwzs.user.dao.IUserDAO;
import com.lhwzs.user.dao.impl.ClassmessageImpl;
import com.lhwzs.user.dao.impl.UserDAOImpl;
import com.lhwzs.user.pojo.Message;
import com.lhwzs.user.pojo.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Auther: 李燦
 * @Date: 2022/5/10 - 05 - 19:05
 * @Decsription: com.lhwzs.user.servlets
 * @version: 1.0
 */
@WebServlet("/student")
public class studentServlet extends ViewBaseServlet {
    private IUserDAO userDAO = new UserDAOImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String operate = request.getParameter("operate");
        if(StringUtil.isEmpty(operate)){
            operate="index";
        }
        switch (operate){
            case "index":
                index(request,response);
                break;
            case "add":
                add(request,response);
                break;
            case "del":
                del(request,response);
                break;
            case "update":
                update(request,response);
                break;
            case "people":
                people(request,response);
                break;
            case "modify":
                modify(request,response);
                break;
            case "modifynicheng":
                modifynicheng(request,response);
                break;
            default:
                throw new RuntimeException("operate非法!");

        }
    }
    private void index(HttpServletRequest request , HttpServletResponse response)throws IOException, ServletException {
        HttpSession session = request.getSession() ;
        Integer pageNo = 1 ;
        String oper = request.getParameter("oper");
        Integer institute = Integer.parseInt(request.getParameter("institute"));
        session.setAttribute("institute",institute);
//        Integer.parseInt(request.getParameter("institute"))
        String keyword = null ;
        if(StringUtil.isNotEmpty(oper) && "search".equals(oper)){
            //说明是点击表单查询发送过来的请求
            //此时，pageNo应该还原为1 ， keyword应该从请求参数中获取
            pageNo = 1 ;
            keyword = request.getParameter("keyword");
            if(StringUtil.isEmpty(keyword)){
                keyword = "" ;
            }
            session.setAttribute("keyword",keyword);
        }else{
            //说明此处不是点击表单查询发送过来的请求（比如点击下面的上一页下一页或者直接在地址栏输入网址）
            //此时keyword应该从session作用域获取
            String pageNoStr = request.getParameter("pageNo");
            if(StringUtil.isNotEmpty(pageNoStr)){
                pageNo = Integer.parseInt(pageNoStr);
            }
            Object keywordObj = session.getAttribute("keyword");
            if(keywordObj!=null){
                keyword = (String)keywordObj ;
            }else{
                keyword = "" ;
            }
        }
        session.setAttribute("pageNo",pageNo);
        IUserDAO daO = new UserDAOImpl();
        List<User> userList = daO.getuserList(keyword,pageNo,institute);
        session.setAttribute("userList",userList);
        //总记录条数
        int fruitCount = daO.getuserCount(keyword,institute);
        //总页数
        int pageCount = (fruitCount+5-1)/5 ;
        session.setAttribute("pageCount",pageCount);
        super.processTemplate("list",request,response);
    }
    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, Object> result = new HashMap<>();
        String maxid=userDAO.getUsernameByMaxId();
        Integer number= Integer.parseInt(maxid.substring(1));
        number++;
        String username= "T"+number;
        String password="123456";
        String nickname = request.getParameter("nickName");
        String sex = request.getParameter("sex") ;
        String phone = request.getParameter("phone");
        String specialty = request.getParameter("specialty");
        int instituteId;
        if(specialty.equals("计算机科学与技术")||specialty.equals("物联网")||specialty.equals("电气工程")||specialty.equals("人工智能")||specialty.equals("软件开发")){
            instituteId=1;
        }else if(specialty.equals("会计")||specialty.equals("金融学")||specialty.equals("财务管理")||specialty.equals("统计学")||specialty.equals("审计")){
            instituteId=2;
        }else {
            instituteId=3;
        }
        User user = new User(0,username , password , nickname , sex,phone,specialty,instituteId) ;
        if(userDAO.adduser(user)>0){
            if(instituteId==1){
                response.sendRedirect("student?institute=1");
            }else if(instituteId==2){
                response.sendRedirect("student?institute=2");
            }else {
                response.sendRedirect("student?institute=3");
            }
        }else {
                System.out.println("添加失败");
        }

    }
    private void del(HttpServletRequest request , HttpServletResponse response)throws IOException, ServletException {
        String userId = request.getParameter("userId");
        String specialty=request.getParameter("specialty");
        int instituteId;
        if(specialty.equals("计算机科学与技术")||specialty.equals("物联网")||specialty.equals("电气工程")||specialty.equals("人工智能")||specialty.equals("软件开发")){
            instituteId=1;
        }else if(specialty.equals("会计")||specialty.equals("金融学")||specialty.equals("财务管理")||specialty.equals("统计学")||specialty.equals("审计")){
            instituteId=2;
        }else {
            instituteId=3;
        }
        if(StringUtil.isNotEmpty(userId)){
            int Id = Integer.parseInt(userId);
            userDAO.deluser(Id);
        }
        if(instituteId==1){
            response.sendRedirect("student?institute=1");
        }else if(instituteId==2){
            response.sendRedirect("student?institute=2");
        }else {
            response.sendRedirect("student?institute=3");
        }
    }
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        //2.获取参数
        String userId = request.getParameter("userId");
        Integer Id = Integer.parseInt(userId);
        String nickname = request.getParameter("nickName");
        String sex = request.getParameter("sex");
        String phone = request.getParameter("phone");
        String specialty = request.getParameter("specialty");
        int instituteId;
        if(specialty.equals("计算机科学与技术")||specialty.equals("物联网")||specialty.equals("电气工程")||specialty.equals("人工智能")||specialty.equals("软件开发")){
            instituteId=1;
        }else if(specialty.equals("会计")||specialty.equals("金融学")||specialty.equals("财务管理")||specialty.equals("统计学")||specialty.equals("审计")){
            instituteId=2;
        }else {
            instituteId=3;
        }
        userDAO.updateuser(new User(Id,nickname,sex,phone,specialty,instituteId));
        //4.资源跳转
        if(instituteId==1){
            response.sendRedirect("student?institute=1");
        }else if(instituteId==2){
            response.sendRedirect("student?institute=2");
        }else {
            response.sendRedirect("student?institute=3");
        }
    }
    private void people(HttpServletRequest request, HttpServletResponse response) throws IOException {
        IUserDAO dao = new ClassmessageImpl();
        Integer userId=Integer.parseInt(request.getParameter("userId"));
        Message message = dao.getclassById(userId);
        request.setAttribute("message",message);
        super.processTemplate("pepole",request,response);
    }
    private void modify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建一个Map集合，存放响应结果
        Map<String,Object> result = new HashMap<>();
        // 处理编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        int userId=Integer.parseInt(request.getParameter("userId"));
        String oldPwd = request.getParameter("oldPassword");
        String newPwd = request.getParameter("newPassword");
        if(userDAO .mima(userId,oldPwd)){
            if(userDAO.updatepwd(userId, newPwd)>0){
                result.put("code",1);
                result.put("msg","密码修改成功！");
            }else{
                result.put("code",0);
                result.put("msg","密码修改失败！");
            }
        }else{
            result.put("code",-1);
            result.put("msg","旧密码输入错误！");
        }
        response.getWriter().write(new Gson().toJson(result));
    }
    private void modifynicheng(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建一个Map集合，存放响应结果
        Map<String,Object> result = new HashMap<>();
        // 处理编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        int userId=Integer.parseInt(request.getParameter("userId"));
        String username = request.getParameter("username");
        if(userDAO.updatenicheng(userId, username)>0){
            result.put("code",1);
            result.put("msg","昵称修改成功！");
        }else{
            result.put("code",0);
            result.put("msg","昵称修改失败！");
        }
        response.getWriter().write(new Gson().toJson(result));
    }
}
